'use strict';

const Controller = require('egg').Controller;
const jwt=require("jsonwebtoken")

// const auth=(token)=>{
//   try{
//     jwt.verify(token,'zm')
//     return true
//   }catch{
//     return false
//   }
// }
class HomeController extends Controller {
  //登录
  async index() {
    const { ctx } = this;
    const {user,pass}=ctx.request.body
    const data=await this.app.mysql.get('user', { user,pass });
    if(data){
      const token=jwt.sign({user,pass},'zm',{expiresIn:"3d"})
      ctx.body = {
        code:200,
        token,
        data:data
      }
    }else{
      ctx.body={
        code:500,
        msg:"登录失败"
      }
    }
  }
  //注册
  async reg() {
    const { ctx } = this;
    const {user,pass,userid}=ctx.request.body
    const data=await this.app.mysql.get('user', { user });
    if(data){
      ctx.body = {
        code:500,
        msg:"用户已存在"
      }
    }else{
      const res= await this.app.mysql.insert('user', { user,pass ,userid:1});
      if(res){
        ctx.body={
          code:200,
          msg:"注册成功"
        }
      }else{
       ctx.boxy={
        code:500,
        msg:"注册失败"
      } 
      }
    }
  }
  //用户名
  async username() {
    const { ctx } = this;
    const {token}=ctx.request.body
    ctx.body={
      code:200,
      user:jwt.verify(token,'zm')
    }
  }
  //获取数据
  async list() {
    const { ctx } = this;
    const data=await this.app.mysql.select('list');
    ctx.body={
      code:200,
      data
    }
  }
  //删除
  async del() {
    const { ctx } = this;
    const {id}=ctx.request.body
    const res=await this.app.mysql.delete('list', {id});
    if(res){
      const data=await this.app.mysql.select('list');
      ctx.body={
        code:200,
        data
      }
    }
  }
}

module.exports = HomeController;
